package com.heima.controller.v1;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.api.R;
//import com.heima.article.service.ApArticleService;
import com.heima.common.constants.ArticleConstants;
import com.heima.common.constants.HotArticleConstants;
import com.heima.common.redis.CacheService;
import com.heima.feign.article.IArticleClient;
import com.heima.model.article.dtos.ArticleHomeDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.mess.UpdateArticleMess;
import com.heima.model.user.dtos.LikesBehaviorDto;
import com.heima.model.user.dtos.UnLikesBehaviorDto;
import com.heima.model.user.dtos.readBehaviorDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.thread.AppThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/v1")
@Slf4j
public class RedisController {
//@Autowired
//private ApArticleService apArticleService;

    @Autowired
    private CacheService cacheService;


    @Autowired
    private KafkaTemplate<String, String> kafkaTemplate;

//    @PostMapping("/likes_behavior")
//    /**
//     * 点赞
//     */
//    public ResponseResult likes(@RequestBody LikesBehaviorDto dto) {
//   //检验参数
//        if (dto==null||dto.getArticleId()==null||checkParam(dto)){
//            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
//        }
//   //是否登入
//        ApUser user = AppThreadLocalUtil.getUser();
//        if (user == null) {
//            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
//        }
//   //修改发送类封装
//        UpdateArticleMess mess = new UpdateArticleMess();
//        mess.setArticleId(dto.getArticleId());
//        mess.setType(UpdateArticleMess.UpdateArticleType.LIKES);
//   //点赞保存数据
//        if (dto.getOperation()==0){
//            Object object = cacheService.hGet("yongHuXingWei:" + user.getId() + "_userId", dto.getArticleId().toString() + "_dz");
//        }
//        return ResponseResult.okResult(dtoString);
//    }

    /**
     * 检查参数
     *
     * @return
     */
    private boolean checkParam(LikesBehaviorDto dto) {
        if (dto.getType() > 2 || dto.getType() < 0 || dto.getOperation() > 1 || dto.getOperation() < 0) {
            return true;
        }
        return false;
    }

//
//    @Autowired
//    private IArticleClient iArticleClient;

    @PostMapping("/likes_behavior")
    /**
     * 点赞
     */
    public ResponseResult likes(@RequestBody LikesBehaviorDto dto) {
        //检验参数
        if (dto == null || dto.getArticleId() == null || checkParam(dto)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //是否登入
        ApUser user = AppThreadLocalUtil.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        String dtoString = JSON.toJSONString(dto);
        //统计封装对象
        UpdateArticleMess mess = new UpdateArticleMess();
        mess.setArticleId(dto.getArticleId());
        mess.setType(UpdateArticleMess.UpdateArticleType.LIKES);

        //点赞数据
        if (dto.getOperation() == 0) {
            mess.setAdd(1);
        } else {
            mess.setAdd(-1);
        }
        cacheService.hPut("yongHuXingWei:" + user.getId() + "_userId", dto.getArticleId().toString() + "_dz", dtoString);
        kafkaTemplate.send(HotArticleConstants.HOT_ARTICLE_SCORE_TOPIC, JSON.toJSONString(mess));
//        iArticleClient.dznum(dto);
        log.info("发送成功！");
        return ResponseResult.okResult(dtoString);
    }


    @PostMapping("/un_likes_behavior")
    /**
     * 不喜欢
     */
    public ResponseResult unlikes(@RequestBody UnLikesBehaviorDto dto) {
        Integer id = AppThreadLocalUtil.getUser().getId();
        String dtoString = JSON.toJSONString(dto);
        StringRedisTemplate stringRedisTemplate = cacheService.getstringRedisTemplate();
        HashOperations<String, Object, Object> opsForHash = stringRedisTemplate.opsForHash();
        //不喜欢数据
        opsForHash.put("yongHuXingWei:" + id + "_userId", dto.getArticleId().toString() + "_bxh", dtoString);
        log.info("不喜欢！");

        return ResponseResult.okResult(dtoString);
    }

    @PostMapping("/read_behavior")
    /**
     * 阅读次数
     */
    public ResponseResult readBehavior(@RequestBody readBehaviorDto dto) {
        //1.检查参数
        if (dto == null || dto.getArticleId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2.是否登录
        ApUser user = AppThreadLocalUtil.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        Integer id = AppThreadLocalUtil.getUser().getId();
        StringRedisTemplate stringRedisTemplate = cacheService.getstringRedisTemplate();
        HashOperations<String, Object, Object> opsForHash = stringRedisTemplate.opsForHash();
        String o = (String) opsForHash.get("yongHuXingWei:" + id + "_userId", dto.getArticleId().toString() + "_yd");
        String dtoString = null;
        if (StringUtils.isNotBlank(o)) {
            readBehaviorDto readBehaviorDto = JSON.parseObject(o, readBehaviorDto.class);
            readBehaviorDto.setCount(readBehaviorDto.getCount() + 1);
            dtoString = JSON.toJSONString(readBehaviorDto);
        } else {
            dto.setCount(1);
            dtoString = JSON.toJSONString(dto);
        }
        //阅读次数
        opsForHash.put("yongHuXingWei:" + id + "_userId", dto.getArticleId().toString() + "_yd", dtoString);
        log.info("阅读次数！");
        //发送消息，数据聚合
        UpdateArticleMess mess = new UpdateArticleMess();
        mess.setArticleId(dto.getArticleId());
        mess.setType(UpdateArticleMess.UpdateArticleType.VIEWS);
        mess.setAdd(1);
        kafkaTemplate.send(HotArticleConstants.HOT_ARTICLE_SCORE_TOPIC,JSON.toJSONString(mess));
        return ResponseResult.okResult(dtoString);
    }


}